import { createRouter, createWebHashHistory } from "vue-router";
import LayOut from "@/views/LayOut.vue";
import { ElMessage } from "element-plus";
import { getToken } from "@/store";
import { LoadingService } from "@/utils";

//記錄歷史訪問路由
const visitedRoute = new Set();

const router = createRouter({
  history: createWebHashHistory(),
  routes: [
    {
      path: "/",
      name: "home",
      component: LayOut,
      children: [
        {
          path: "/abnormal/apply",
          name: "apply",
          component: () => import("../views/ApplyAbnormal.vue"),
        },
        {
          path: "/abnormal/quit",
          name: "quit",
          component: () => import("../views/QuitAbnormal.vue"),
        },
        {
          path: "/bedmove/movequery",
          name: "movequery",
          component: () => import("../views/MoveQuery.vue"),
        },
        {
          path: "/home",
          name: "homeview",
          component: () => import("../views/HomeView.vue"),
        },
      ],
    },
    {
      path: "/:pathMatch(.*)*",
      name: "NotFound",
      component: () => import("../views/NotFound.vue"),
    },
    {
      path: "/login",
      name: "login",
      component: () => import("../views/LoginView.vue"),
    },
  ],
});

router.beforeEach(async (to) => {
  //首次加載開啟loading
  if (!visitedRoute.has(to.path)) {
    LoadingService.open();
  }

  if ((getToken() === "" || getToken() === null) && to.name !== "login") {
    ElMessage({
      type: "error",
      message: "請先登錄",
      offset: 30,
    });
    return { name: "login" };
  }
});

router.afterEach((to) => {
  if(!visitedRoute.has(to.path)){
    visitedRoute.add(to.path)
    LoadingService.close()
  }
});

export default router;
